<template>
  <el-dialog v-model="addFieldDialogInfo.dialogVisible" :title="addFieldDialogInfo.title" width="500px"
    @close="closeAddFieldDialog" :close-on-click-modal="false">
    <el-form v-if="addFieldDialogInfo.dialogVisible" ref="addFieldFormRef" :model="addFieldForm" label-position="top"
      :rules="addFieldRules">
      <el-form-item label="字段标识(必须以custom_开头)" prop="name">
        <el-input v-model="addFieldForm.name" placeholder="请输入字段标识" show-word-limit :maxlength="30" />
      </el-form-item>
      <el-form-item label="字段名称" prop="title">
        <el-input v-model="addFieldForm.title" show-word-limit :maxlength="20" placeholder="请输入字段名称" />
      </el-form-item>
      <el-form-item label="字段类型" prop="type">
        <el-select v-model="addFieldForm.type" placeholder="请选择" @change="handleSelectFieldTypeChange">
          <el-option v-for="item in fieldTypeList" :label="item.name" :value="item.value" :key="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="addFieldForm.type === 'select'" label="待选值" prop="options">
        <el-input v-model="optionValue" maxlength="20" show-word-limit>
          <template #append>
            <el-button type="success" :disabled="optionValue === ''" @click="addOption">确认</el-button>
          </template>
        </el-input>
        <div class="mt-1 flex flex-col w-100%">
          <VueDraggable v-model="addFieldForm.options" handle=".handle" :animation="150">
            <div v-for="(item, index) in addFieldForm.options" :key="index"
              class="p-5px h-22px pl-10px pr-10px flex items-center justify-between b-rd-4px b-1px b-solid b-#eee option-list mb-5px">
              <div class="w-70% flex items-center">
                <el-icon class="cursor-pointer handle mr-5px">
                  <Rank />
                </el-icon>
                <div :title="item.label" class="overflow-hidden whitespace-nowrap text-ellipsis">
                  {{ item.isDefault ? `(默认值)` : '' }}{{ item.label }}
                </div>
              </div>
              <div class="w-25% flex items-center justify-between">
                <div class="cursor-pointer font-size-14px color-#409eff" @click="switchDefault(item, index)">{{
                  item.isDefault ?
                    '清除默认' : '设为默认' }}</div>
                <el-icon class="cursor-pointer" @click="addFieldForm.options.splice(index, 1)">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </VueDraggable>
        </div>
      </el-form-item>
      <el-form-item label="是否必填" prop="required">
        <el-select v-model="addFieldForm.required" placeholder="请选择">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="addFieldForm.type === 'input'" label="默认值" prop="defaultValue">
        <el-input show-word-limit :maxlength="addFieldForm.type === 'input' ? 200 : 500"
          v-model="addFieldForm.defaultValue" />
      </el-form-item>
      <el-form-item label="字段描述" prop="remark">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="说明字段目标、注意事项等" show-word-limit
          :maxlength="200" v-model="addFieldForm.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="text-right">
        <el-button @click="closeAddFieldDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirmAddField">确定</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import { queryFieldTypeList } from '@/api/field'
import { ElMessage, type ElForm } from 'element-plus'
import { VueDraggable } from 'vue-draggable-plus'
import { type IFieldForm } from '@/api/field/types'

const emits = defineEmits(['submitField'])

const addFieldDialogInfo = ref({
  dialogVisible: false,
  title: '',
  type: ''
})

const fieldInfo = ref<any>({})

const fieldTypeList = ref<any[]>([])
const optionValue = ref<string>('')

const initForm = { name: 'custom_', title: '', type: '', options: [], defaultValue: '', remark: '', required: false, rules: [] }

const addFieldForm = ref<IFieldForm & { [key: string]: any }>({ name: 'custom_', title: '', type: '', options: [], defaultValue: '', remark: '', required: false, rules: [] });
const addFieldFormRef = useTemplateRef<InstanceType<typeof ElForm>>('addFieldFormRef');

const addFieldRules = ref({
  name: [
    { required: true, message: '请输入字段标识', trigger: 'blur' },
    { pattern: /^custom_.+$/, message: '字段标识不能只是custom_，请补充内容', trigger: 'blur' },
  ],
  title: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择字段类型', trigger: 'change' }]
});

const openAddFieldDialog = (type: string, data?: IFieldForm) => {
  addFieldDialogInfo.value.type = type
  addFieldDialogInfo.value.dialogVisible = true
  if (type === 'edit') {
    addFieldDialogInfo.value.title = '编辑字段';
    if (data) {
      Object.keys(addFieldForm.value) // 遍历当前表单字段，确保类型安全
        .forEach((key) => {
          if (Reflect.has(data, key)) {
            (addFieldForm.value as any)[key] = (data as any)[key]
          }
        })
    }

  } else {
    addFieldDialogInfo.value.title = '新增字段'
  }
  getFieldTypeList()
}

const closeAddFieldDialog = () => {
  addFieldDialogInfo.value = {
    type: '',
    dialogVisible: false,
    title: ''
  }
  addFieldForm.value = JSON.parse(JSON.stringify(initForm))
}

const handleConfirmAddField = () => {
  addFieldFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    const obj = addFieldForm.value
    if (obj.required) {
      obj.rules.push({ required: true, message: '请输入' + obj.title, trigger: 'blur' })
    }
    emits('submitField', JSON.parse(JSON.stringify(obj)), addFieldDialogInfo.value.type)
    closeAddFieldDialog()
  })
}

const switchDefault = (item: any, index: number) => {
  if (item.isDefault) {
    addFieldForm.value.options[index].isDefault = false
    addFieldForm.value.defaultValue = ''
  } else {
    addFieldForm.value.options.forEach((item: any) => {
      item.isDefault = false
    })
    addFieldForm.value.options[index].isDefault = true
    addFieldForm.value.defaultValue = addFieldForm.value.options[index].value
  }
}

const handleSelectFieldTypeChange = (e: string) => {
  if (e === 'input') {
    addFieldForm.value.options = [];
  }
  addFieldForm.value.defaultValue = ''
}

const getFieldTypeList = async () => {
  const res:any = await queryFieldTypeList()
  if (res.code === 0) {
    fieldTypeList.value = [...res.data]
  }
}

const addOption = () => {
  const options = addFieldForm.value.options
  if (options.some(item => item.value === optionValue.value)) {
    ElMessage.error('选项值[' + optionValue.value + ']已存在，请勿重复')
    return;
  }
  addFieldForm.value.options.push({
    label: optionValue.value,
    value: optionValue.value,
    isDefault: false
  })
  optionValue.value = ''
}

defineExpose({ openAddFieldDialog })
</script>

<style lang="scss" scoped></style>
